<template>
  <div class="dashboard-container">
    <!-- 顶部数据卡片 -->
    <el-row :gutter="20" class="stats-cards">
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card" style="background: linear-gradient(to right, #6dd5ed, #2193b0);">
          <div class="card-content">
            <div class="icon-wrapper">
              <el-icon>
                <Box/>
              </el-icon>
            </div>
            <div class="text-wrapper">
              <div class="card-title">产品总数</div>
              <div class="card-value">{{ stats.productCount }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <!-- 其他三个卡片... -->
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card" style="background: linear-gradient(to right, #ff9966, #ff5e62);">
          <div class="card-content">
            <div class="icon-wrapper">
              <el-icon>
                <Platform/>
              </el-icon>
            </div>
            <div class="text-wrapper">
              <div class="card-title">工位总数</div>
              <div class="card-value">{{ stats.workstationCount }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card"
                 style="background: linear-gradient(to right, #aa4b6b, #6b6b83, #3b8d99);">
          <div class="card-content">
            <div class="icon-wrapper">
              <el-icon>
                <Clock/>
              </el-icon>
            </div>
            <div class="text-wrapper">
              <div class="card-title">待加工工件</div>
              <div class="card-value">{{ stats.waitingPieceCount }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card" style="background: linear-gradient(to right, #11998e, #38ef7d);">
          <div class="card-content">
            <div class="icon-wrapper">
              <el-icon>
                <Open/>
              </el-icon>
            </div>
            <div class="text-wrapper">
              <div class="card-title">正在加工工件</div>
              <div class="card-value">{{ stats.processingPieceCount }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" style="margin-top: 20px;">
      <el-col :span="16">
        <el-card shadow="never">
          <div ref="chartRef" style="width: 100%; height: 350px;"></div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card shadow="never" class="info-card" style="height: 100%;">
          <template #header>
            <div class="card-header"><span>系统信息</span></div>
          </template>
          <div class="info-item"><span>前端框架:</span>
            <el-tag>Vue 3</el-tag>
          </div>
          <div class="info-item"><span>UI 框架:</span>
            <el-tag type="success">Element-Plus</el-tag>
          </div>
          <div class="info-item"><span>图表库:</span>
            <el-tag type="danger">ECharts</el-tag>
          </div>
          <div class="info-item"><span>后端框架:</span>
            <el-tag type="info">Spring Boot</el-tag>
          </div>
          <div class="info-item"><span>数据访问:</span>
            <el-tag type="warning">MyBatis-Plus</el-tag>
          </div>
          <div class="info-item"><span>API 文档:</span>
            <el-tag>Knife4j</el-tag>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 欢迎语区域 -->
    <el-row style="margin-top: 20px;">
      <el-col :span="24">
        <el-card shadow="never" class="welcome-card">
          <h2 class="welcome-title">欢迎使用 MES 核心调度系统！</h2>
          <p class="welcome-text">
            在这里，可以管理生产计划，监控工位实时状态，并触发智能调度算法来优化生产流程。
          </p>
          <div class="quick-links">
            <el-button type="primary" plain @click="$router.push('/mes/pplan-management')">创建生产计划</el-button>
            <el-button type="success" plain @click="$router.push('/mes/workstation-board')">查看工位看板</el-button>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import {ref, reactive, onMounted, onBeforeUnmount, nextTick} from 'vue'
import {getDashboardStats, getWorkstationLoad} from '@/api/modules/dashboard'
import {Box, Platform, Clock, Open} from '@element-plus/icons-vue'
import * as echarts from 'echarts'

const stats = reactive({
  productCount: 0,
  workstationCount: 0,
  waitingPieceCount: 0,
  processingPieceCount: 0,
})
const chartRef = ref(null)
let myChart = null

const fetchStats = async () => {
  try {
    const data = await getDashboardStats()
    Object.assign(stats, data)
  } catch (error) {
    console.error("获取统计数据失败", error)
  }
}

const initChart = async () => {
  try {
    const chartData = await getWorkstationLoad();

    if (!chartRef.value) return;

    if (myChart) {
      myChart.dispose();
    }

    myChart = echarts.init(chartRef.value);

    const option = {
      title: {text: '各工位实时任务负载', textStyle: {fontSize: 16, fontWeight: 'normal'}},
      tooltip: {trigger: 'axis', axisPointer: {type: 'shadow'}},
      grid: {left: '3%', right: '4%', bottom: '3%', containLabel: true},
      xAxis: {
        type: 'category',
        data: chartData.map(item => item.stationName),
        axisLabel: {interval: 0, rotate: 30}
      },
      yAxis: {type: 'value', name: '任务数'},
      series: [{
        data: chartData.map(item => item.taskCount),
        type: 'bar',
        barWidth: '60%',
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            {offset: 0, color: '#83bff6'},
            {offset: 0.5, color: '#188df0'},
            {offset: 1, color: '#188df0'}
          ])
        },
        emphasis: {
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              {offset: 0, color: '#2378f7'},
              {offset: 0.7, color: '#2378f7'},
              {offset: 1, color: '#83bff6'}
            ])
          }
        },
      }]
    };

    myChart.setOption(option);

  } catch (error) {
    console.error("获取或渲染图表数据失败", error)
  }
}

const resizeChart = () => {
  if (myChart) {
    myChart.resize();
  }
}

onMounted(() => {
  fetchStats();

  nextTick(() => {
    initChart();
  });

  window.addEventListener('resize', resizeChart);
});

onBeforeUnmount(() => {
  if (myChart) {
    myChart.dispose();
  }
  window.removeEventListener('resize', resizeChart);
});
</script>

<style scoped>
.dashboard-container {
  padding: 20px;
}

.stats-cards {
  margin-bottom: 20px;
}

.stat-card {
  color: white;
  border: none;
  border-radius: 8px;
}

.stat-card .card-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.stat-card .icon-wrapper {
  font-size: 52px;
  opacity: 0.8;
}

.stat-card .text-wrapper {
  text-align: right;
}

.stat-card .card-title {
  font-size: 16px;
  margin-bottom: 10px;
}

.stat-card .card-value {
  font-size: 28px;
  font-weight: bold;
}

.welcome-card {
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.welcome-title {
  margin-top: 0;
  font-size: 24px;
  color: #333;
}

.welcome-text {
  line-height: 1.8;
  color: #666;
  margin-bottom: 25px;
  font-size: 14px;
}

.info-card .card-header {
  font-weight: bold;
}

.info-card .info-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 13px 0;
  border-bottom: 1px solid #f0f2f5;
  font-size: 14px;
}

.info-card .info-item:last-child {
  border-bottom: none;
}

.info-card .info-item span:first-child {
  color: #606266;
}
</style>
